﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Common;
using ESOL.Business.Bpt;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.MasterData;
using ESOL.Business.Sec;
using ESOL.WinUI.Hr;
using ESOL.Common.Schema;

namespace ESOL.WinUI.Bpt
{
    public partial class frmMaintainDesignTask : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public BptDrawBlueprintEntity SelectedBptDrawBlue { get; set; }
        private List<BptDrawBlueprintItemEntity> DeleteList = new List<BptDrawBlueprintItemEntity>();
        #endregion

        #region Constructor
        public frmMaintainDesignTask()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbState, "DBT", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbAppType, "DT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(StatusItem, "DBT", true);
            List<MstPersonEntity> listPerson = new List<MstPersonEntity>();
            if (Common.CommonParameter.CurrentUser.PersonEntity == null)
            {
                listPerson = MstPersonBs.GetMstPersonAllList(false);
            }
            else
            {
                MstPersonBs.GetPersonListBySupervisor(CommonParameter.CurrentUser.PersonId, listPerson);
            }
            cmbDrawPerson.DataSource = listPerson;
            cmbDrawPerson.DisplayMember = "NameCn";
            cmbDrawPerson.ValueMember = "PersonId";
        }

        private void BindDataGridDetail()
        {
            if (SelectedBptDrawBlue == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataTable dt = BptDrawBlueprintItemBs.GetDrawBuleItemByID(SelectedBptDrawBlue.DrawBlueprintId);
            if (dt == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            dt.AcceptChanges();
            gvDetail.DataSource = dt;
            DeleteList = new List<BptDrawBlueprintItemEntity>();

        }

        private void BindFilesGridView()
        {
            if (SelectedBptDrawBlue == null)
            {

                gvFileList.DataSource = null;
                return;
            }
            BptApplicationEntity bptentity = new BptApplicationEntity();
            bptentity = BptApplicationBs.GetBptappByDrawBlueID(SelectedBptDrawBlue.DrawBlueprintId);
            DataTable dt = BptApplicationAttachedBs.GetFilesAppByID(bptentity.ApplicationId);
            if (dt == null)
            {
                gvFileList.DataSource = null;
                return;
            }
            dt.AcceptChanges();
            gvFileList.DataSource = dt;
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedBptDrawBlue == null)
            {
                return;
            }
            if (ThisActionType == ActionType.New)
            {
                txtTaskCode.Text = "自动生成";
            }
            else
            {
                txtTaskCode.Text = SelectedBptDrawBlue.TaskCode;//制图任务单号
            }
            DataTable dt = new DataTable();
            string sCondition = "and a.DRAW_BLUEPRINT_ID='" + SelectedBptDrawBlue.DrawBlueprintId + "'";
            string sOrderBy = "TASK_CODE";
            dt = BptDrawBlueprintBs.GetCustomerByCondition(sCondition, sOrderBy, "100");
            if (dt.Rows.Count > 0)
            {
                txtCoustomer.Text = dt.Rows[0]["CUSTOMER_NAME"].ToString();
                txtAppDepartment.Text = dt.Rows[0]["DEPARTMENT_NAME"].ToString();
                txtApplicationCode.Text = dt.Rows[0]["APPLICATION_CODE"].ToString();
                if (string.IsNullOrEmpty(dt.Rows[0]["SHEDULED_DATE"].ToString()) == false)
                {
                    dtpFilshDate.EditValue = Convert.ToDateTime(dt.Rows[0]["SHEDULED_DATE"].ToString());
                }

            }
            cmbState.SetSelectedValue(SelectedBptDrawBlue.Status);//状态
            cmbAppType.SetSelectedValue(SelectedBptDrawBlue.ApplicationType);
            cmbDrawPerson.SetSelectedValue(SelectedBptDrawBlue.DrawingPerson);
            txtRemark.Text = SelectedBptDrawBlue.Remark;//备注
        }

        private void SetEntity()
        {
            SelectedBptDrawBlue.Remark = txtRemark.Text;
            SelectedBptDrawBlue.ApplicationType = cmbAppType.SelectedValue.ToString();

            if (!txtApproveby.Text.Equals(""))
            {
                MstPersonEntity AppPerson = (MstPersonEntity)txtApproveby.Tag;
                SelectedBptDrawBlue.ApprovedBy = AppPerson.PersonId;
            }
            if (ThisActionType == ActionType.New)
            {
            }
            if (ThisActionType == ActionType.Modify)
            {
                if (SelectedBptDrawBlue.Status == "DBT01")
                {
                    if (cmbState.SelectedValue.ToString() == "DBT06")
                    {
                        SelectedBptDrawBlue.Status = "DBT06";
                    }
                    else
                    {
                        SelectedBptDrawBlue.Status = "DBT02";
                    }
                }
                else
                {
                    SelectedBptDrawBlue.Status = cmbState.SelectedValue.ToString();
                }
                SelectedBptDrawBlue.DrawingPerson = cmbDrawPerson.SelectedValue.ToString();
                SelectedBptDrawBlue.SheduledDate = (DateTime)dtpFilshDate.EditValue;
            }
            if (ThisActionType == ActionType.Approve)
            {
            }
        }

        private bool CheckData()
        {
            if (cmbDrawPerson.SelectedValue==null||
                string.IsNullOrEmpty(cmbDrawPerson.SelectedValue.ToString()))
            {
                MessageBox.Show("执行人人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpFilshDate.EditValue == null)
            {
                MessageBox.Show("计划完成日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = BptDrawBlueprintBs.UpdateBptDrawBlueprintUpdateItems(SelectedBptDrawBlue);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void SendMessage(string sMessageTitle, string sSender, string sMessageBody, string MessageLevel)
        {
            MstMessageEntity message = new MstMessageEntity();
            message.MessageId = Guid.NewGuid().ToString();
            message.MessateTitle = sMessageTitle;
            message.MessageSender = sSender;
            message.MessageBody = sMessageBody;
            message.MessageLevel = MessageLevel;
            message.FormName = "ESOL.WinUI.Bpt.frmDrawBlueprintManage";
            message.MessageDate = DateTime.Now;
            MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedBptDrawBlue.DrawingPerson);
            List<MstPersonEntity> toList = new List<MstPersonEntity>();
            toList.Add(person);
            MstMessageBs.SendMessage(message, toList);
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            BindComboBox();
            SetFields();
            BindFilesGridView();
            base.OnShown(e);
        }

        private void txtApproveby_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApproveby.Text = frm.SelectedPerson.NameCn;
                txtApproveby.Tag = frm.SelectedPerson;
            }
            else
            {
                txtApproveby.Text = "";
                txtApproveby.Tag = null;
            }
        }

        DataRow drAttachmentSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drAttachmentSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                SendMessage("新制图任务", CommonParameter.CurrentUser.PersonId, "有新的制图任务了；", MessageLevel.ML03.ToString());
                this.DialogResult = DialogResult.OK;
            }
        }

        private void tsmNewAttachment_Click(object sender, EventArgs e)
        {
            if (SelectedBptDrawBlue.Status != "DBT02")
            {
                MessageBox.Show("任务状态错误，无法新增附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (gvFileList.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvFileList.DataSource;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDeleteAttachment_Click(object sender, EventArgs e)
        {
            if (SelectedBptDrawBlue.Status != "DBT02")
            {
                MessageBox.Show("当前模式下，不允许删除附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (gvFileList.DataSource == null)
            {
                return;
            }
            if (drAttachmentSelected == null)
            {
                return;
            }
            BptApplicationAttachedEntity Attentity = new BptApplicationAttachedEntity(drAttachmentSelected);
            bool result = BptApplicationAttachedBs.DeleteBptApplicationAttached(Attentity);
            if (result)
            {
                MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("删除失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (SelectedBptDrawBlue.Status != "DBT02")
            {
                MessageBox.Show("任务状态错误，无法上传附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "图片文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "图片文件(*.jpg,*.pdf)|*.jpg;*.pdf";
            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;
            if (op.ShowDialog() == DialogResult.OK)
            {
                drAttachmentSelected["FILE_NAME"] = op.FileName;
            }
        }

        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drAttachmentSelected == null)
            {
                return;
            }
            BptApplicationAttachedEntity Attentity = new BptApplicationAttachedEntity(drAttachmentSelected);
            EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
            if (string.IsNullOrEmpty(Attentity.AttachedId))
            {
                MessageBox.Show("请先保存附件后再下载！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                string sFileName = Attentity.AttachedId + Attentity.FileName.Substring(Attentity.FileName.Length - 4);
                byte[] bytes = EService.DownLodeBptappfiles(sFileName);
                if (bytes != null)
                {
                    if (sFileName.Substring(sFileName.Length - 3).ToUpper().Equals("JPG"))
                    {
                        Image img = CommonFunctions.byteArrayToImage(bytes);
                        string ssrt = "C:" + @"\" + "TempPictures" + @"\" + sFileName;
                        img.Save(ssrt);
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        string fileName = ssrt;
                        process.StartInfo.FileName = fileName;
                        process.StartInfo.Arguments = "rundll32.exe C:\\WINDOWS\\system32\\shimgvw.dll,ImageView_Fullscreen";
                        process.StartInfo.UseShellExecute = true;
                        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                        process.Start();
                        process.Close();
                    }
                    if (sFileName.Substring(sFileName.Length - 3).ToUpper().Equals("PDF"))
                    {
                        string ssrt = "C:" + @"\" + "TempPictures" + @"\" + sFileName;
                        FileStream fs;
                        if (System.IO.File.Exists(ssrt))
                        {
                            fs = new FileStream(ssrt, FileMode.Truncate);
                        }
                        else
                        {
                            fs = new FileStream(ssrt, FileMode.CreateNew);
                        }
                        BinaryWriter br = new BinaryWriter(fs);
                        br.Write(bytes, 0, bytes.Length);
                        br.Close();
                        fs.Close();
                        System.Diagnostics.Process.Start(ssrt);
                    }
                }
                else
                {
                    MessageBox.Show("找不到对应图片！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请先选择一行记录！");
            }
        }

        private void repositoryItemButtonEdit3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (SelectedBptDrawBlue.Status != "DBT02")
            {
                MessageBox.Show("任务状态错误，不允许保存附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(drAttachmentSelected["FILE_NAME"].ToString()))
            {
                MessageBox.Show("请先选择需要上传的附件后再保存！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!System.IO.File.Exists(drAttachmentSelected["FILE_NAME"].ToString()))
            {
                MessageBox.Show("文件不存在，请重新选择！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DialogResult dlresult = MessageBox.Show("是否上传并保存附件！", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dlresult == DialogResult.OK)
            {
                string sRemarks = "";
                if (string.IsNullOrEmpty(drAttachmentSelected["REMARK"].ToString()) == false)
                {
                    sRemarks = drAttachmentSelected["REMARK"].ToString();
                }
                BptApplicationAttachedEntity Attentity;
                if (drAttachmentSelected.RowState != DataRowState.Added)
                {
                    Attentity = new BptApplicationAttachedEntity(drAttachmentSelected);
                }
                else
                {
                    BptApplicationEntity bptentity = new BptApplicationEntity();
                    bptentity = BptApplicationBs.GetBptappByDrawBlueID(SelectedBptDrawBlue.DrawBlueprintId);
                    Attentity = new BptApplicationAttachedEntity();
                    Attentity.AttachedId = Guid.NewGuid().ToString();
                    Attentity.BptApplicationId = bptentity.ApplicationId;
                    Attentity.Remark = sRemarks;
                    Attentity.FileName = drAttachmentSelected["FILE_NAME"].ToString();
                    Attentity.FileType = "提交附件";//申请时上传的文件用0标示，提交任务时上传的文件用1标示
                    Attentity.UploadBy = Common.CommonParameter.CurrentUser.PersonId;
                    Attentity.UploadDate = DateTime.Now;
                }
                if (Attentity.FileType != "提交附件")
                {
                    MessageBox.Show("不能修改申请人上传的文件，请重新选择！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                bool result = BptApplicationBs.SaveBptAppfiles(Attentity, drAttachmentSelected.RowState.ToString());
                if (result)
                {
                    MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void cmbState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.Modify)
            {
                if (cmbState.SelectedValue.ToString().Equals("DBT03"))
                {
                    MessageBox.Show("当前状态下不可选择此项！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbState.SelectedValue = SelectedBptDrawBlue.Status;
                }
                if (cmbState.SelectedValue.ToString().Equals("DBT05"))
                {
                    MessageBox.Show("当前状态下不可选择此项！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbState.SelectedValue = SelectedBptDrawBlue.Status;
                }
                if (cmbState.SelectedValue.ToString().Equals("DBT04"))
                {
                    MessageBox.Show("当前状态下不可选择此项！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbState.SelectedValue = SelectedBptDrawBlue.Status;
                }
            }
        }

        private void repositoryItemButtonEdit4_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                BptBlueprintEntity bptEntity = new BptBlueprintEntity();
                bptEntity = BptBlueprintBs.GetBptBlueprintByProductID(frm.SelectedProduct.ProductId);
                if (bptEntity == null)
                {
                    MessageBox.Show("该编码没有导图记录！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                drTaskItemSelected["BLUEPRINT_CODE"] = bptEntity.BlueprintCode;
                SelectedBptDrawBlue.BlueprintId = bptEntity.BlueprintId;
                drTaskItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drTaskItemSelected["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
            }
        }

        DataRow drTaskItemSelected;
        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drTaskItemSelected = gridView2.GetDataRow(e.FocusedRowHandle);
        }
        #endregion
    }
}
